

package com.base.lock.autoconfigure;
import com.base.lock.*;
import com.base.lock.aop.LockAnnotationAdvisor;
import com.base.lock.aop.LockInterceptor;
import com.base.lock.executor.LockExecutor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import java.util.List;


/**
 * 分布式锁自动配置器
 *
 * @author carl
 */
@Configuration
@EnableConfigurationProperties({LockProperties.class})
@ConditionalOnProperty(prefix = "lock",name = "primary-executor")
@RequiredArgsConstructor
public class LockAutoConfiguration {

    @Autowired
    private final LockProperties properties;

    @SuppressWarnings("rawtypes")
    @Bean
    @ConditionalOnMissingBean
    public LockTemplate lockTemplate(LockFailureStrategy lockFailureStrategy, List<LockExecutor> executors) {
        LockTemplate lockTemplate = new LockTemplate();
        lockTemplate.setProperties(properties);
        lockTemplate.setLockFailureStrategy(lockFailureStrategy);
        lockTemplate.setExecutors(executors);
        return lockTemplate;
    }

    @Bean
    @ConditionalOnMissingBean
    public LockKeyBuilder lockKeyBuilder() {
        return new DefaultLockKeyBuilder();
    }

    @Bean
    @ConditionalOnMissingBean
    public LockFailureStrategy lockFailureStrategy() {
        return new DefaultLockFailureStrategy();
    }

    @Bean
    @ConditionalOnMissingBean
    public LockInterceptor lockInterceptor(LockTemplate lockTemplate, LockKeyBuilder lockKeyBuilder) {
        return new LockInterceptor(lockTemplate, lockKeyBuilder);
    }

    @Bean
    @ConditionalOnMissingBean
    public LockAnnotationAdvisor lockAnnotationAdvisor(LockInterceptor lockInterceptor) {
        return new LockAnnotationAdvisor(lockInterceptor, Ordered.HIGHEST_PRECEDENCE);
    }

}
